   
            
            //todo: sum paytypes from sales and payments
            //
            
            var db;
            var dbSaleName = '';
            var dbSaleItemName = '';
            var dbSalePaymentName = '';
            var CustomerPaymentDBName = '';
			var searchBookmark = 0;
            
            init();
			
			var query = location.search;
            var id = query.substring(query.indexOf("id=") + 3, query.length);
            
            if (id == 'aging' ) 
            	ChangeTab(1);
			else
				ChangeTab(0);

            
            
            function ChangeTab(item){
            
                if (item == 8) //datepad
                    document.all.datepad.style.display = 'inline';
                else 
                    document.all.datepad.style.display = 'none';
				 if (item == 1) //customer payments
					{
						LoadYears2();
						LoadAging(currentDate.getFullYear(), 0);
						document.all.agingtab.style.display = 'inline';
					}
					else 
						document.all.agingtab.style.display = 'none';
					
                if (item == 0) //info
                    document.all.infotab.style.display = 'inline';
                else 
                    document.all.infotab.style.display = 'none';
            }
            
            function FixDate(option){
            
                var from = document.all.fromdate;
                var to = document.all.todate;
                var currentDate = new Date();
                
                if (option == 1) //day 
                {
                    var fromdate = currentDate.getDate();
                    
					from.value = currentDate.getMonth() + 1 + '/' + fromdate + '/' + currentDate.getFullYear();
                    to.value = currentDate.getMonth() + 1 + '/' + fromdate + '/' + currentDate.getFullYear();
                }
                if (option == 2) //month 
                {
                    var month = currentDate.getMonth();
                    month++;
                    
                    lastday = '/30/';
					if(month==0 | month==2 | month==4 | month==6| month==7| month==9| month==11)
						lastday = '/31/';
					if(month==1)
					{	if(currentDate.getFullYear() % 4 == 0)
							lastday = '/29/';
						else
							lastday = '/28/';
					}
					
                    from.value = month + '/01/' + currentDate.getFullYear();
                    to.value = month + lastday + currentDate.getFullYear();
                }
                if (option == 3) //year
                {
                    from.value = '01/01/' + currentDate.getFullYear();
                    to.value = '12/31/' + currentDate.getFullYear();
                }
                var fromd = new Date(from.value);
                
                //if(fromd.getFullYear() != tod.getFullYear())
                //	{
                //	alert('Dates must be within same year');
                //return;
                //}
                
                dbSaleName = 'Sale_' + fromd.getFullYear();
                dbSaleItemName = 'SaleItem_' + fromd.getFullYear();
                dbSalePaymentName = 'SalePayment_' + fromd.getFullYear();
                CustomerPaymentDBName = 'CustomerPayment_' + fromd.getFullYear();
                
                LoadSales(from.value, to.value);
            }
            
			
            function LoadSales(from, to){
            
               //alert(from.value);
                var from1 = new Date(from);
                var to1 = new Date(to);
                
				from1.setDate(from1.getDate() - 1);
				to1.setDate(to1.getDate() + 1);
            	var fromd = FormatDate((from1.getMonth()+1)+ '/'+ from1.getDate() +'/' +from1.getFullYear());
                var tod = FormatDate((to1.getMonth()+1)+ '/'+ to1.getDate() +'/' +to1.getFullYear());
                
                var query = "select sum(qty*price) as sales, sum(qty*cost), ";
                query += "sum(taxes) as tax ";
                query += " from " + dbSaleItemName;
                //alert(from);
                if (to != null) {
                    query += " inner join " + dbSaleName + " on " + dbSaleName + ".id=saleid"
                    query += " where saledate >'" + fromd + "' and saledate <'" + tod + "'";
                    
                }
                
                var html = "";
                var totalspan = document.all.results;
                //totalspan.innerHTML = query;
                try {
                    var rs = db.execute(query);
                } 
                catch (ex) {
                    totalspan.innerHTML = 'No results found';
                    return;
                }
                // alert(query);
                
                
                html += "<table class='reportheader' border='1'>";
                html += "<tr ><td colspan='2'>Totals</td></tr>";
                if (rs.isValidRow()) {
                    try {
                        var sales = new Number(rs.field(0));
                        var costs = new Number(rs.field(1));
                        var taxes = new Number(rs.field(2));
                        var profits = new Number();
                        profits = sales - costs;
                        html += "<tr><td width='100px'  style='text-align:left;'>Sales</td><td width='100px' style='text-align:right;'>" + formatNumber(rs.field(0), true) + "</td></tr>";
                        html += "<tr><td width='100px'  style='text-align:left;'>Costs</td><td width='100px' style='text-align:right;'>" + formatNumber(rs.field(1), true) + "</td></tr>";
                        html += "<tr><td width='100px'  style='text-align:left;'>Taxes</td><td width='100px' style='text-align:right;'>" + formatNumber(rs.field(2), true) + "</td></tr>";
                        html += "<tr><td width='100px'  style='text-align:left;'>Profits</td><td width='100px' style='text-align:right;'>" + formatNumber(profits, true) + "</td></tr>";
                    } 
                    catch (ex) {
                    
                    }
                    
                }
                rs.close();
                
                
                //customer payments
                query = "select sum(amount) from " + CustomerPaymentDBName;
                if (from != null) 
                    query += " where paymentdate >'" + fromd + "' and paymentdate <'" + tod + "'";
                rs = db.execute(query);
                if (rs.isValidRow()) {
                    try {
                        html += "<tr><td width='100px'  style='text-align:left;'>Payments</td><td width='100px' style='text-align:right;'>" + formatNumber(rs.field(0), true) + "</td></tr>";
                    } 
                    catch (ex) {
                    }
                    
                }
                rs.close();
				
				//customer pending balances
                query = "select sum(balance), 'Balances' from Customer "
			    rs = db.execute(query);
                if (rs.isValidRow()) {
                    try {
                        html += "<tr><td width='100px'  style='text-align:left;'>Pending Balances</td><td width='100px' style='text-align:right;'>" + formatNumber(rs.field(0), true) + "</td></tr>";
                    } 
                    catch (ex) {
                    }
                    
                }
                rs.close();
				
				
                //income
                query = "select sum(total), paytype from (select sum(amount) as total, paytype from " + dbSalePaymentName
                if (to != null) {
                    query += " inner join " + dbSaleName + " s on s.id=saleid ";
                    query += " where saledate >'" + fromd + "' and saledate <'" + tod + "' group by paytype ";
                }
                else 
                    query += " group by paytype ";
                
                query += " union select sum(amount),paytype from " + CustomerPaymentDBName;
                if (to != null) {
                    query += " where paymentdate >'" + fromd + "' and paymentdate <'" + tod + "'";
                }
                query += " group by paytype) as totals group by paytype";
                //totalspan.innerHTML = query;
				
                rs = db.execute(query);
                while (rs.isValidRow()) {
                    try {
                        html += "<tr><td width='100px'  style='text-align:left;'>" + rs.field(1) + "</td><td width='100px' style='text-align:right;'>" + formatNumber(rs.field(0), true) + "</td></tr>";
                    } 
                    catch (ex) {
                    }
                    rs.next();
                    
                }
                
                html += "</table>";
                
                totalspan.innerHTML = html;
                rs.close();
                
            }
            
            
            // Open this page's local database.
            function init(){
                var success = false;
                
                if (window.google && google.gears) {
                    try {
                        db = google.gears.factory.create('beta.database');
                        
                        if (db) {
                            db.open('psdb');
                            
                            
                            /*
                             var currentDate = new Date();
                             dbSaleName = "Sale_" + currentDate.getFullYear();
                             dbSaleItemName = "SaleItem_" + currentDate.getFullYear();
                             dbSalePaymentName = "SalePayment_" + currentDate.getFullYear();
                             CustomerPaymentDBName = 'CustomerPayment_' + currentDate.getFullYear();
                             */
                            success = true;
                            // Initialize the UI at startup.
                        
                            //displayRecentPhrases();
                            // loadSaleTypes('');
                        }
                        
                    } 
                    catch (ex) {
                        setError('Could not create database: ' + ex.message);
                        alert('Could not create database: ' + ex.message);
                    }
                }
                
                // Enable or disable UI elements
                
                var inputs = document.forms[0].elements;
                for (var i = 0, el; el = inputs[i]; i++) {
                    el.disabled = !success;
                }
                
            }
			
			 function LoadAging(search, option){
                try {
					
					CustomerPaymentDBName = 'CustomerPayment_' + search;
					
					searchBookmark = searchBookmark + option;
					if (searchBookmark < 0) 
						searchBookmark = 0;
					
					var query = "select c.id, firstname,middlename,lastname, balance, max(paymentdate) as lastpayment, round(julianday('now') - julianday(max(paymentdate))) as days from customer c inner join "+CustomerPaymentDBName+" cp on c.id=customerid group by c.id,balance,firstname,middlename,lastname having balance > 0 and julianday('now') - julianday(max(paymentdate))>30 order by 7 desc ";
					query += ' limit 10 offset ' + searchBookmark;
						
					
					var status = document.all.results;
					//status.innerHTML =query;
					//return;
					status.innerHTML = '<div class="field" >Search Results:</div>';//'Searching...' ;
					var rs = db.execute(query);
					var html = "";
					var count = new Number(0);
					while (rs.isValidRow()) {
						var link = "<a href='customerpie_bu.html?id="+rs.field(0)+"'>Load</a>";
						html += SearchResult2(link, getFullName(rs.field(1), rs.field(2), rs.field(3)), 'Last: ' + rs.field(5), 'Bal: ' + formatNumber(rs.field(4), true),'<span style="font-size:8px">Days:'+ rs.field(6)+ "</span>");
						count++;
						rs.next();
					}
					
					if (searchBookmark >= 10) 
						html += "<a href=# onclick='LoadAging(\"" + search + "\",-10);'>[Back]</a>";
					if (count >= 10) 
						html += "<a href=# onclick='LoadAging(\"" + search + "\",10);'>[Next]</a>";
					
						status.innerHTML = html;
					rs.close();
				} 
				catch (ex) {
					status.innerHTML = 'No records found';
					//alert(ex);
				}
                
            }
			
             function LoadYears2(){
                // if (!google.gears.factory || !db) {
                //     alert('Error saving');
                //     return;
                // }
                var yearspan = document.all.years;
                var html = "<select id='yearselect' style='font-size:medium;' onchange='LoadAging(this.value,0);' >"
                // var rs = db.execute("select distinct substr(name, length(name)-3) from sqlite_master where type='table' and  name like '%_20%'");
                var i = new Number(2007);
                var j = new Number(currentDate.getFullYear());
                
                //while (rs.isValidRow()) {
                for (i = 2007; i <= j; i++) {
                    //html += "<option value='" + rs.field(0) + "'";
                    html += "<option value='" + i + "'";
                    //if (rs.field(0) == new Date().getFullYear())
                    if (i == new Date().getFullYear()) 
                        html += " selected ";
                    //html += ">" + rs.field(0) + "</option>";
                    html += ">" + i + "</option>";
                    //rs.next();
                }
                //rs.close();
                html += "</select>";
                yearspan.innerHTML = html;
            }
        